const mysql = require('mysql');
const config = require('../config/db');
const dayjs = require("dayjs");
const fs = require("fs");

class DataBase {
    constructor(mysql) {
        this.now = () => dayjs().format('YYYY-MM-DD HH:mm:ss')
        this.pool = mysql.createPool(config)
        this.pool.getConnection((err, connection) => {
            if (err) return this.pool.emit('error', err)
            // connection.query('select * from songshu.user', (err, result, fields) => {
            //     if (err) return this.pool.emit('error', err)
            // })
            connection.release()
        })
        this.pool.on('connection', () => console.log('数据库连接成功！', this.now()));
        this.pool.on('release', connection => console.log('Connection %d released to ' + connection.threadId + ' ' + this.now()))
        this.pool.on('error', err => {
            // writeErrLog(undefined, err.name || '', err.code || '', err.message || '')
            //新增错误日志写到文件 控制台记录发生时间 错误更新到mysql
            //sql报错就写入此文件触发刷新
            console.log(`emit sql error . five seconds after restart process！`, err.message, this.now(), "5秒后重新连接");
            setTimeout(() => {
                fs.writeFileSync('./refresh.js', ';', {encoding: 'utf8'})
            }, 5000)
        })
    }

    actuator(sql, values) {
        //执行器封装，向外延申的函数都会汇聚到这里
        return new Promise((resolve, reject) => {
            this.pool.getConnection((err, connection) => {
                if (err) return reject({
                    code: 0,
                    error: {
                        sql,
                        message: err.sqlMessage,
                        code: err.code
                    }
                })
                connection.query(sql, values, (err, results, fields) => {
                    if (err) return reject(err)
                    resolve({
                        message: '执行成功！',
                        results,
                        sql
                    })
                })
                connection.release()
            })
        })
    }
}

module.exports = new DataBase(mysql)
